<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/18
 * Time: 19:39
 */

namespace App\Http\Middleware;
use App\traits\RbacTrait;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminAuthMiddleware
{
    use  RbacTrait ;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next,$guard = null)
    {
        $user = null ;
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('backend/login');
            }
        }
        // 设置user
        $request->setUserResolver(function() use ($guard) {
            return Auth::guard($guard)->user() ;
        });

        //是否有权限访问
        $this->checkUser($request) ;
        return $next($request);
    }

    protected  function checkUser(Request $request){
        $user = $request->user();

        if(in_array($user->name,config('rbac.allowUsers'))){
            return true ;
        }

        $path = $request->getPathInfo();
        $path = substr($path,1) ;
        $prefixPos = strpos($path , '/') ;

        if ($prefixPos !== false){
            $path = substr($path , $prefixPos + 1) ;

            if(empty($path) || $this->mathRules($path,$request->method(),config('rbac.allowRules'))){
                return ;
            }

            if(!$user->CheckRule($path,$request->method())){
                abort(403);
            }
        }
    }
}